/**
 * 
 */
package touro.mancala.client;

import java.util.ArrayList;

/**
 * @author Baila
 *
 */
public class Move {

	private Pit startPit;
	private GameState state = GameState.getGameState();
	private Board board = state.getBoard();
	private Store[] pits = board.getPitsAndStores();
	
	public Move(int i) throws Exception
	{
		//try to cast Store to Pit, if can't cast it then invalid move
		
		if(!(pits[i] instanceof Pit)){
			throw new Exception("You cannot sow from a store.");
		}
		startPit = (Pit) pits[i];
		
		if (!state.getActivePlayer().equals(startPit.getPlayer())) {
			throw new Exception("You cannot move the other player's pieces.");
		}
		if (startPit.getSize()==0) {
			throw new Exception("You cannot sow from an empty pit.");
		}
		
		

	}

	public boolean sow() {
		ArrayList<Stone> stones = startPit.removeStones();

		int place = startPit.getPlace();

		for (Stone s : stones) {
			place++;
			place = place%14;
			boolean placed = false;
			while (!placed) {
				if (pits[place] instanceof Pit || pits[place].getPlayer().equals(startPit.getPlayer())) {
					pits[place].addStone(s);
					placed = true;
				} else {
					place++;
					place = place%14;
				}
			}
		}
		//place is now the place of the last stone sown. It must have been sown either in the
		//player's store or in any of the pits so the if statements check where it was sown
		boolean isPlayerMyPlayer = pits[place].getPlayer().equals(startPit.getPlayer());
		if (!(pits[place] instanceof Pit) && isPlayerMyPlayer) {
			return true;
		} else if (isPlayerMyPlayer && pits[place].getSize() == 1 && pits[12-place].getSize() > 0){
			Store myStore = board.getMyStore(pits[place].getPlayer());
			ArrayList<Stone> myStones = ((Pit)pits[place]).removeStones();
			ArrayList<Stone> otherStones = ((Pit)pits[12-place]).removeStones();
			myStore.addStone(myStones);
			myStore.addStone(otherStones);
		}
		return false;
	}	
}
